# -*- coding: utf-8 -*-
# Project : flacon
# File : flaconglobal.py
# (c) Alexander Sokolov sokoloff.a@gmail.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.


import exceptions
import subprocess
import os
import signal

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
import errors
from settings import *


#****************************************************************
# Supported input format
#****************************************************************
class InputAudioFormat:
    def __init__(self, ext, name, programs):
        self.ext = ext
        self.name = name
        self.programs = programs
        settings.addPrograms(programs)


#****************************************************************
# All supported input formats
#****************************************************************
class InputAudioFormats:
    APE   = 'APE'
    FLAC  = 'FLAC'
    WV    = 'WV'
    WAV   = 'WAV'
    TTA   = 'TTA'

    formats = {
        APE:  InputAudioFormat('ape',  'APE',     ['mac']),
        FLAC: InputAudioFormat('flac', 'FLAC',    ['flac']),
        WV:   InputAudioFormat('wv',   'WavPack', ['wvunpack']),
        TTA:  InputAudioFormat('tta',  'TTA',     ['ttaenc']),
        WAV:  InputAudioFormat('wav',  'WAV',     []),

    }


#****************************************************************
# Supported output format
#****************************************************************
class OutputAudioFormat:
    def __init__(self):
        self.ext = QString()
        self.name = QString()
        self.encoderClass = None
        self.trackGainClass = None
        self.albomGainClass = None
        self.id = QString()




#****************************************************************
# All supported output formats
#****************************************************************
class OutputAudioFormats:

   #****************************************************************
   #
   #****************************************************************
    def __init__(self):
        self.formats = {}


   #****************************************************************
   #
   #****************************************************************
    def add(self, encoderClass):
        format = OutputAudioFormat()
        format.id = encoderClass.id
        format.ext = encoderClass.extension
        format.name = encoderClass.name

        format.encoderClass = encoderClass
        settings.addPrograms(encoderClass.programs())

        format.trackGainClass = encoderClass.trackGainClass()
        if format.trackGainClass:
            settings.addPrograms(format.trackGainClass.programs())

        format.albumGainClass = encoderClass.albumGainClass()
        if format.albumGainClass:
            settings.addPrograms(format.albumGainClass.programs())

        format.configPageClass = encoderClass.configPageClass()
        if format.configPageClass:
            settings.addDefaults(format.configPageClass.defaults())

        self.formats[encoderClass.id] = format
        self.__dict__[encoderClass.id] = encoderClass.id


   #****************************************************************
   #
   #****************************************************************
    def __getitem__(self, index):
        return self.formats[str(index)]


   #****************************************************************
   #
   #****************************************************************
    def keys(self):
        return self.formats.keys()


   #****************************************************************
   #
   #****************************************************************
    def items(self):
        return self.formats.items()


   #****************************************************************
   #
   #****************************************************************
    def current(self):
        key = str(settings.value("OutFiles/Format").toString())
        try:
            return self.formats[key]
        except KeyError:
            return self.formats['FLAC']


outputAudioFormats = OutputAudioFormats()


#****************************************************************
#
#****************************************************************
class Statuses:
    NotRunning  = 0
    Canceled    = 1
    Error       = 2
    Aborted     = 3
    OK          = 4
    Extracting  = 5
    Encoding    = 6
    Queued      = 7
    WaitGain    = 8
    CalcGain    = 9
    WriteGain   = 10



#****************************************************************
#
#****************************************************************
class ReplayGainTypes:
    Disable     = 'Disable'
    Track       = 'Track'
    Album       = 'Album'


#****************************************************************
#  Compatible with python < 2.6
#****************************************************************
try:
    subprocess.Popen.terminate
except AttributeError:
    subprocess.Popen.terminate = lambda self: os.kill(self.pid, signal.SIGTERM)



#****************************************************************
#
#****************************************************************
def tryPopen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False,
                shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0):

    if isinstance(args, QStringList):
        _args = []
        for s in args:
            _args.append(unicode(s))
    else:
        _args = args


    try:
        return subprocess.Popen(_args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds,
                     shell, cwd, env, universal_newlines, startupinfo, creationflags)

    except OSError, e:
        raise errors.ProgramNotFoundError(QString(_args[0]))




#****************************************************************
#
#****************************************************************
def pipeToQString(pipe):
    codec = QTextCodec.codecForLocale()
    lines = QStringList()
    for line in pipe:
        lines << codec.toUnicode(line)

    return lines.join("\n")


#****************************************************************
#
#****************************************************************
def pipeToStr(pipe):
    return unicode(pipeToQString(pipe))


#****************************************************************
#
#****************************************************************
def modulesDir():
    return os.path.dirname(__file__)



